package com.dxy.yesas2020goals.study.partone.disignpattern.cmdpattern.ftp;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;

public class SocketPool {
	private static List<ServerSocket2> sockets = new ArrayList<ServerSocket2>();

	public static class ServerSocket2 extends ServerSocket {
		private boolean closed = false;
		private Object closeLock = new Object();

		public ServerSocket2(int port) throws IOException {
			super(port);
		}

		@Override
		public void close() throws IOException {
			synchronized (closeLock) {
				closed = true;
			}

		}

		public boolean isClosed2() {
			synchronized (closeLock) {
				return closed;
			}
		}
	}

	public static ServerSocket2 getServerSocket() throws IOException {
		ServerSocket2 socket = null;
		for (int i = 0; i < sockets.size(); i++) {
			socket = sockets.get(i);
			if (socket.isClosed2()) {
				return socket;
			}
		}
		socket = new ServerSocket2(0);
		sockets.add(socket);
		return socket;
	}
}
